//新的数据上传了
module.exports = function(data) {
    var defer = require('q').defer();
    //2分钟后触发统计方法
    setTimeout((function(d) {
        return function() {
            handle(d).then(function() {
                defer.resolve();
            });
        };
    })(data), 1);
    return defer.promise;
};

//处理该事件,首先要给每个项目的审核人发一封邮件,告诉他们有新数据上传,需要他们审核
function handle(data) {
    var defer = require('q').defer();
    var Project = require('./../../models/Project.js');
    var mailSend = require('./../../service/mailSend.js');
    var extend = require('extend');
    var prj = new Project(data.prjId);
    prj.getReviewerList()
        .then(function(reviewerList) {
            if (data.notify === 1) {
                var redisClient = require('redis').createClient();
                var nameSpace = require('./../../config.json').redisNamespace;
                var redisKey = nameSpace + ":notify:reviewer:" + data.prjId + ":" + data.date;
                //在redis里设定当前项目是否需要通知审核人,如果不存在key,就通知,否则不通知
                redisClient.get(redisKey, function(err, reply) {
                    if (err || !reply) {
                        reviewerList.forEach(function(reviewer) {
                            var objData = extend(data, reviewer);
                            mailSend.notifyDataReviewer(objData, objData.mail);
                        });
                        //通知微信上的审核人
                        notifyWechatUser(data, reviewerList);
                        redisClient.set(redisKey, 1); //存入Redis
                        //2小时内自动销毁
                        redisClient.expire(redisKey, 3600 * 2);
                        redisClient.quit();
                    }
                    defer.resolve();
                });
            } else {
                defer.resolve();
            }
        });
    return defer.promise;
}


//通知微信后台的审核人
function notifyWechatUser(data, reviewerList) {
    var weUserList = reviewerList.filter(function(item) {
        return item.wechatId ? true : false;
    });
    if (weUserList.length > 0) {
        data.reviewerList = weUserList;
        var request = require('request');
        request({
            method: 'POST',
            url: "http://wechat.ce-safe.com/review",
            json: data
        }, function(error, response, body) {
            if (!error) {
                defer.resolve(body);
            } else {
                defer.reject();
            }
        });
    }
}
